Page({
  data: {
    phone: '',
    verifyCode: '',
    password: '',
    confirmPassword: '',
    isAgreed: false,
    countdown: 0,
    nickname: ''
  },

  onPhoneChange(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  onCodeChange(e) {
    this.setData({
      verifyCode: e.detail.value
    });
  },

  onPasswordChange(e) {
    this.setData({
      password: e.detail.value
    });
  },

  onConfirmPasswordChange(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },

  onNicknameChange(e) {
    this.setData({
      nickname: e.detail.value
    });
  },

  onAgreementChange(e) {
    this.setData({
      isAgreed: e.detail.checked
    });
  },

  getVerifyCode() {
    if (!this.data.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }
    if (this.data.countdown > 0) {
      return;
    }
    wx.request({
      url: 'https://api.example.com/send-verify-code',
      method: 'POST',
      data: {
        phone: this.data.phone
      },
      success: () => {
        this.setData({
          countdown: 60
        });
        this.startCountdown();
      }
    });
  },

  startCountdown() {
    const timer = setInterval(() => {
      if (this.data.countdown <= 0) {
        clearInterval(timer);
        return;
      }
      this.setData({
        countdown: this.data.countdown - 1
      });
    }, 1000);
  },

  handleRegister() {
    const { phone, password, confirmPassword, nickname } = this.data;
    if (!phone || phone.length !== 11) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    if (!password || password.length < 6) {
      wx.showToast({
        title: '密码至少6位',
        icon: 'none'
      });
      return;
    }
    if (password !== confirmPassword) {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'none'
      });
      return;
    }
    wx.showLoading({ title: '注册中...' });
    wx.cloud.callFunction({
      name: 'userAuth',
      config: {
        env: 'cloud1-6gz10xdd7d0548eb'
      },
      data: {
        action: 'register',
        phone: phone,
        password: password,
        nickname: nickname
      },
      success: res => {
        wx.hideLoading();
        if (res.result.code === 0) {
          wx.showToast({ title: '注册成功', icon: 'success' });
          setTimeout(() => {
            wx.redirectTo({ url: '/pages/login/index' });
          }, 1500);
        } else {
          wx.showToast({ title: res.result.msg, icon: 'none' });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ title: '注册失败', icon: 'none' });
      }
    });
  },

  goBack() {
    wx.navigateBack();
  },

  viewAgreement() {
    wx.navigateTo({
      url: '/pages/agreement/index'
    });
  },

  navigateToLogin() {
    wx.navigateTo({
      url: '/pages/login/index'
    });
  }
});